// 检查是否为移动端
let isMobile = window.innerWidth < 768

function getDynamicSpaceBetween() {
    return window.innerWidth * .10625;
}

let mySwiper = new Swiper ('.swiper', {
    direction: 'horizontal', // 垂直切换选项
    loop: true, // 循环模式选项
    spaceBetween: 40, // 图片间距
    slidesPerView: 'auto',  // 让每个图片按原大小显示
    grabCursor: true, // 启用抓取光标
    speed: 800, // 动画过渡时间，单位：毫秒，500毫秒为默认
    keyboard: {
        enabled: true, // 键盘控制启用
    },
    mousewheel: {
        enabled: true, // 滑轮控制启用
    },
    scrollbar: {
        el: '.swiper-scrollbar', // 滑块滚动条
        draggable: true, // 启用拖拽
        hide: true, // 滚动条是否隐藏
        snapOnRelease: true, // 释放后自动对齐
    },
    breakpoints: {
        767: {
            slidesPerView: 2,
            spaceBetween: getDynamicSpaceBetween(),
            centeredSlides: true, // 取消居中
        },
    },
    on: {
        resize: function () {
            let isMobile = window.innerWidth < 768
            if (isMobile) {
                mySwiper.slidesPerView = 2
                mySwiper.spaceBetween = getDynamicSpaceBetween()
                mySwiper.centeredSlides = true
            } else {
                mySwiper.slidesPerView = 2
                mySwiper.spaceBetween = 40
                mySwiper.centeredSlides = false
            }
            mySwiper.update(); // 更新实例
        },
    }
})

let isDragging = false;
const images = document.querySelectorAll('.swiper-slide img');
let currentIndex = 0;
const overlay = document.querySelector('.overlay');
const overlayContent = overlay.querySelector('.overlay-content');
const overlayImg = overlayContent.querySelector('#overlay-img');
const prevBtn = overlayContent.querySelector('#prev-btn');
const nextBtn = overlayContent.querySelector('#next-btn');
const close = overlayContent.querySelector('.close-overlay');

// 监听鼠标按下事件
images.forEach((img, index) => {
    img.addEventListener('click', function (e) {
        if (!isDragging) {
            if (isMobile) {
                // 移动端点击中间的图放大显示
                if (e.target.closest('.swiper-slide').classList.contains('swiper-slide-active')) {
                    clearInterval(autoplayInterval)
                    openImageInOverlay(e.target.src, index);
                } else if (e.target.closest('.swiper-slide').classList.contains('swiper-slide-prev')) {
                    mySwiper.slidePrev();
                    resetAutoplay()
                } else {
                    mySwiper.slideNext();
                    resetAutoplay()
                }
            } else {
                // 触发点击放大的逻辑
                openImageInOverlay(e.target.src, index);
            }
        }
    });
});

// 打开图片的放大版
function openImageInOverlay(src, index) {
    overlayImg.src = src;  // 设置放大图片的源
    currentIndex = index;  // 更新当前图片的索引

    // 在图片加载完成后去掉淡出效果并展示新的图片
    overlayImg.onload = () => {
        overlay.classList.add('active');
        setTimeout(() => {
            overlayContent.classList.add('show'); // 让图片展示出来
        }, 50); // 小延时以保证动画效果
    };

}

// 点击关闭蒙层
overlay.addEventListener('click', function (e) {
    if (e.target === overlay) {
        overlayContent.classList.remove('show'); // 关闭动画
        setTimeout(() => {
            overlay.classList.remove('active')  // 关闭蒙层
            isMobile ? startAutoplay() : null
        }, 300);
    }
});

// 点击切换上一张
prevBtn.addEventListener('click', function () {
    // 禁用按钮
    prevBtn.disabled = true;
    setTimeout(() => prevBtn.disabled = false, 300); // 启用按钮

    // 给当前图片添加淡出效果
    overlayImg.classList.add('fade-out');

    // 等待上一张图片淡出后切换
    setTimeout(() => {
        currentIndex = (currentIndex === 0) ? images.length - 1 : currentIndex - 1;
        overlayImg.src = images[currentIndex].src;  // 更新图片源
    }, 300); // 等待 300ms 让图片淡出完成

    // 图片加载完成后淡入新图片
    overlayImg.onload = () => {
        overlayImg.classList.remove('fade-out');
    };
});

// 点击切换下一张
nextBtn.addEventListener('click', function () {
    // 禁用按钮
    nextBtn.disabled = true;
    setTimeout(() => nextBtn.disabled = false, 300); // 启用按钮

    // 给当前图片添加淡出效果
    overlayImg.classList.add('fade-out');

    // 等待上一张图片淡出后切换
    setTimeout(() => {
        currentIndex = (currentIndex === images.length - 1) ? 0 : currentIndex + 1;
        overlayImg.src = images[currentIndex].src;  // 更新图片源
    }, 300); // 等待 300ms 让图片淡出完成

    // 图片加载完成后淡入新图片
    overlayImg.onload = () => {
        overlayImg.classList.remove('fade-out');
    };
});

close.addEventListener('click', () => {
    overlayContent.classList.remove('show'); // 关闭动画
    setTimeout(() => {
        overlay.classList.remove('active')  // 关闭蒙层
        isMobile ? startAutoplay() : null
    }, 300);
})

/* 自动播放 */
let autoplayInterval = null; // 保存自动播放的定时器
let autoplayDelay = 5000; // 自动切换的时间间隔，单位毫秒

// 1. 添加自动播放功能
function startAutoplay() {
    if (autoplayInterval) {
        clearInterval(autoplayInterval); // 如果已经有定时器，先清除
    }

    autoplayInterval = setInterval(() => {
        mySwiper.slideNext();  // 切换到下一张
    }, autoplayDelay); // 每5秒切换一次
}

// 2. 监听手动切换时，重新开始自动播放
function resetAutoplay() {
    clearInterval(autoplayInterval);  // 清除定时器
    startAutoplay();  // 重新开始定时器
}

// 在初始化时启动自动播放
if (isMobile) {
    startAutoplay();
} else {
    clearInterval(autoplayInterval)
}

// 移动端-小箭头滚动首屏
function scrollDown() {
    $('.scroll-down').on('click',  () => {
        const screenHeight = window.innerHeight;
        $('html, body').animate(
            { scrollTop: screenHeight },
            800,
            'swing'
        );
    });
}

// 移动端-切换菜单显隐
function toggleMenu() {
    document.querySelector('.mobile-menu-title-btn').addEventListener('click', () => {
        document.querySelector('.mobile-menu-content').classList.toggle('show')
    })
}

// 移动端-滚动菜单显隐
function toggleMenuOnScroll() {
    const mobileMenu = document.querySelector('.mobile-menu');
    const triggerHeight = window.innerHeight / 2; // 一屏高度的一半
    const menuContent = document.querySelector('.mobile-menu-content')

    window.addEventListener('scroll', () => {
        const scrollY = window.scrollY || window.pageYOffset; // 当前滚动位置
        if (scrollY >= triggerHeight) {
            mobileMenu.classList.add('show'); // 添加 'show' 类
        } else {
            mobileMenu.classList.remove('show'); // 移除 'show' 类
            menuContent.classList.remove('show');
        }
    });
}

// 初始化菜单项的点击事件处理，包括高亮和滚动到相应部分的功能。
function initializeMenuInteractions() {
    const menuList = isMobile ? document.querySelectorAll('.mobile-menu-content li') : document.querySelectorAll('.navi-block-menu li');
    const sectionClassNames = ['index', 'activity-background', 'activity-profile', 'purpose-significance', 'activity-requirement', 'wonderful-review']
    const menuContent = document.querySelector('.mobile-menu-content')
    menuList.forEach((li, index) => {
        li.addEventListener('click', () => {
            menuList.forEach(li => li.classList.remove('is_active'));
            li.classList.add('is_active');
            const sectionClassName = sectionClassNames[index]
            const currentURL = window.location.href
            if (index === 0) {
                window.scrollTo({
                    left: 0,
                    top: 0,
                    behavior: 'smooth'
                });
                isMobile ? menuContent.classList.remove('show') : null
            }
            else {
                if (!currentURL.includes('index.ftl')) {
                    window.location.href = `index.ftl?section=${sectionClassName}`
                } else {
                    toAnchorView(sectionClassName)
                    isMobile ? menuContent.classList.remove('show') : null
                }
            }
        })
    })
}

// 平滑过渡到对应区域 - 执行函数
function toAnchorView(data) {
    const $choose = document.querySelector(`.${data}`);
    if ($choose) {
        const commonCard = $choose.closest('.common-card');
        if (isMobile) {
            // 移动端，需要额外向上偏移 -48px
            const scrollPosition = $choose.getBoundingClientRect().top + window.scrollY;
            const offset = scrollPosition - 48; // 计算偏移量，减去 48px 以让出顶部导航栏的位置
            window.scrollTo({
                left: 0,
                top: offset,
                behavior: 'smooth'
            });
        } else {
            // 非移动端，正常滚动
            commonCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }
}

// 滚动检测高亮函数
function highlightOnScroll() {
    const banner = document.querySelector('.banner')
    const mbBanner = document.querySelector('.mobile-player-block')
    const sections = Array.from(document.querySelectorAll('.common-card-title'))
    isMobile ? sections.unshift(mbBanner) : sections.unshift(banner)

    const menuList = isMobile
        ? Array.from(document.querySelectorAll('.mobile-menu-content li'))
        : Array.from(document.querySelectorAll('.navi-block-menu li'))
    const range = isMobile ? 100 : 300; // 可视区域范围

    const rects = sections.map(section => section.getBoundingClientRect());

    let activeIndex = -1;
    for (let i = 0; i < rects.length; i++) {
        const rect = rects[i];
        // 标题处于可视范围内时，立即高亮第一个符合条件的标题
        if (rect.top >= 0 && rect.top <= range) {
            activeIndex = i;
            // console.log('1',activeIndex)
            break;
        }
        // 上一个标题已超出可视区域，但下一个标题未进入可视区域底部
        if (rect.top < 0 && rects[i + 1] && rects[i + 1].top > document.documentElement.clientHeight) {
            activeIndex = i;
            // console.log('2',activeIndex)
            break;
        }
        // 上一个标题已超出可视区域，但下一（多）个标题已进入可视区域但大于range区域
        if (rect.top < 0 && rects[i + 1] && (rects[i + 1].top < document.documentElement.clientHeight && rects[i + 1].top > range)) {
            activeIndex = i;
            // console.log('3',activeIndex)
            break;
        }
        // 最后一个标题特殊处理：滚动到底部时高亮
        if (rect.top < 0 && !rects[i + 1]) {
            activeIndex = i;
            // console.log('5',activeIndex)
        }
    }
    // 重置所有菜单的高亮
    menuList.forEach(li => li.classList.remove('is_active'));
    // 为检测到的当前区域对应的菜单项添加高亮
    if (activeIndex !== -1) {

        const activeSection = sections[activeIndex].getAttribute('data-section');
        menuList.forEach(item => {
            if (item.getAttribute('data-section') === activeSection) {
                item.classList.add('is_active');
            }
        });
    }
}

// 防抖函数
function debounce(func, delay) {
    let timer;
    return function() {
        clearTimeout(timer);
        timer = setTimeout(func, delay);
    };
}
const debouncedHighlightOnScroll = debounce(highlightOnScroll, 100);

window.addEventListener('DOMContentLoaded', () => {
    scrollDown()
    toggleMenu()
    // toggleMenuOnScroll()
    initializeMenuInteractions()
})

window.addEventListener('scroll', () => {
    debouncedHighlightOnScroll()
})

window.addEventListener('resize', () => {
    isMobile = window.innerWidth < 768
    isMobile ? startAutoplay() : clearInterval(autoplayInterval)
    initializeMenuInteractions()
})
